<template>
  <div style="display: flex;flex-direction: column">
    <div style="display: flex;justify-content: center">
      <el-button style="width: 212px;" type="primary" icon="el-icon-plus"
                 @click="()=>showSubscriptionServiceFlag=true">
        {{ i18nt('designer.setting.subscriptionService') }}
      </el-button>
    </div>
    <div class="ds-list">
      <el-scrollbar v-if="!!formConfig.serviceVersionVOs && (formConfig.serviceVersionVOs.length > 0)">
        <div v-for="(svvo,index) in formConfig.serviceVersionVOs" :key="svvo.id" class="service-item">
          <div class="font-bolder">{{ svvo.service.name }}</div>
          <div style="color:red">{{ svvo.service.code }}</div>
          <div style="justify-self: end">
            <el-button type="primary" icon="el-icon-edit" plain circle
                       size="small" @click="showAndEditSubscriptionServiceDialog(svvo.id)"></el-button>
            <el-popconfirm :title="`确认删除服务${svvo.service.name}吗?`" @confirm="handleRemoveService(svvo.id)">
              <template #reference>
                <el-button type="danger" icon="el-icon-delete" plian circle
                           size="small"></el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </el-scrollbar>
      <template v-else>
        <el-empty :description="i18nt('designer.setting.noDataSource')"></el-empty>
      </template>
    </div>
  </div>


  <!--  服务订阅-->
  <!--  <el-drawer :title="i18nt('designer.setting.subscriptionService')" v-model="showSubscriptionServiceFlag">-->
  <custom-dialog v-model="showSubscriptionServiceFlag"
                 v-if="showSubscriptionServiceFlag"
                 width="80%"
                 top="40px"
                 :title="i18nt('designer.setting.subscriptionService')"
                 :draggable="false"
                 :show-close="false"
                 :close-on-press-escape="false"
                 :close-on-click-modal="false"
  >
    <subscription-service ref="subscriptionService" :form-config="formConfig" />
    <template #footer>
      <el-button type="primary" @click="syncServicesToFormConfig">保存</el-button>
      <el-button @click="closeSubscriptionServiceDialog">取消</el-button>
    </template>
  </custom-dialog>

  <!--  </el-drawer>-->
  <div v-if="showTestDataSourceDialogFlag" class="">
    <el-dialog :title="i18nt('designer.setting.testDataSource')" v-model="showTestDataSourceDialogFlag"
               :show-close="true" class="drag-dialog small-padding-dialog" append-to-body
               :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <el-alert type="info" :closable="false" :title="i18nt('designer.setting.dsvTitle')"></el-alert>
      <code-editor :mode="'json'" :readonly="false" v-model="dsvJson" class="dsv-json-editor"></code-editor>
      <div class="footer-button">
        <el-button type="primary" @click="doDataSourceRequest">{{ i18nt('designer.setting.executeDataSource') }}
        </el-button>
        <el-button type="primary" plain @click="clearRequestResult">{{ i18nt('designer.setting.clearRequestResult') }}
        </el-button>
        <el-button @click="showTestDataSourceDialogFlag = false">
          {{ i18nt('designer.hint.closePreview') }}
        </el-button>
      </div>
      <el-alert type="info" :closable="false" :title="i18nt('designer.setting.dsRequestResult')"></el-alert>
      <code-editor :mode="'json'" :readonly="true" v-model="dsResultJson" ref="dsResultEditor"></code-editor>
    </el-dialog>
  </div>

  <div v-if="showImportDSDialogFlag" class="">
    <el-dialog :title="i18nt('designer.setting.importDataSource')" v-model="showImportDSDialogFlag"
               :show-close="true" class="drag-dialog small-padding-dialog" center
               append-to-body :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <el-alert type="info" :title="i18nt('designer.hint.importDSHint')" show-icon class="alert-padding"></el-alert>
      <code-editor :mode="'json'" :readonly="false" v-model="importDSTemplate"></code-editor>
      <el-switch v-model="clearOldDSFlag" style="margin-top: 10px"
                 :active-text="i18nt('designer.setting.clearExistingDataSource')"
                 :inactive-text="i18nt('designer.setting.remainExistingDataSource')"></el-switch>
      <div slot="footer" class="dialog-footer-center">
        <el-button type="primary" @click="doImportDataSource">
          {{ i18nt('designer.hint.import') }}
        </el-button>
        <el-button @click="showImportDSDialogFlag = false">
          {{ i18nt('designer.hint.cancel') }}
        </el-button>
      </div>
    </el-dialog>
  </div>

  <div v-if="showExportDSDialogFlag" class="">
    <el-dialog :title="i18nt('designer.setting.exportDataSource')" v-model="showExportDSDialogFlag"
               :show-close="true" class="drag-dialog small-padding-dialog" center
               :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <el-tabs type="border-card" class="no-box-shadow no-padding" v-model="activeExportTab"
               @tab-click="handleExportTabClick">
        <el-tab-pane :label="i18nt('designer.setting.selectDataSourceForExport')" name="setting">
          <div v-if="exportDSArray && (exportDSArray.length > 0)" class="export-ds-list">
            <el-descriptions v-for="(ds, dsIdx) in exportDSArray" :key="dsIdx"
                             :column="1" size="small" border>
              <template #title>
                <span :title="ds.description">{{ ds.uniqueName }}</span>
              </template>
              <template #extra>
                <el-checkbox v-model="ds.checked" @change="handleExportDSChange">
                  {{ i18nt('designer.setting.dataSourceChecked') }}
                </el-checkbox>
              </template>
              <el-descriptions-item>
                <template #label>
                  <div :title="ds.requestURL">
                    <el-icon>
                      <platform />
                    </el-icon>
                  </div>
                </template>
                {{ ds.requestURL }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <template v-else>
            <el-empty :description="i18nt('designer.setting.noDataSource')"></el-empty>
          </template>
        </el-tab-pane>
        <el-tab-pane :label="i18nt('designer.setting.previewDataSourceExportResult')" name="result">
          <code-editor :mode="'json'" :readonly="true" v-model="dsExportContent" ref="exportDSEditor"></code-editor>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer-center">
        <el-button type="primary" class="copy-json-btn" :data-clipboard-text="dsRawExportContent"
                   @click="copyDataSourceJson">
          {{ i18nt('designer.hint.copyJson') }}
        </el-button>
        <el-button type="" @click="showExportDSDialogFlag = false">
          {{ i18nt('designer.hint.closePreview') }}
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script lang="ts">
import i18n from '@/utils/i18n'
import CodeEditor from '@/components/code-editor/index.vue'
import { Platform } from '@element-plus/icons-vue'
import SubscriptionService
  from '@/components/form-designer/setting-panel/data-source-setting/subscription-service/index.vue'
import CustomDialog from '@/components/common/custom-dialog/index.vue'
import { FormConfig, FormDesigner } from '@/types/form'
import { PropType } from 'vue'
import { traverseAllWidgets } from '@/utils/util'
import eventBus from '@/utils/event-bus'

import { SERVICE_OPERATION } from '@/utils/constants'

export default {
  name: 'data-source-setting',
  mixins: [i18n],
  inject: {
    getGlobalDsv: {
      default: () => {
      },
    },
  },
  components: {
    CustomDialog,
    SubscriptionService,
    Platform,
    CodeEditor,
  },
  props: {
    designer: Object as PropType<FormDesigner>,
    formConfig: Object as PropType<FormConfig>,
  },
  data() {
    return {
      //activeNames: ['2'],
      activeNames: '2',

      dsModel: {
        dataSourceId: null,
        uniqueName: '',
        requestURL: '',
        requestURLType: 'String',
        description: '',
        headers: [],
        params: [],
        data: [],
        requestMethod: 'get',
        configHandlerCode: '  return config',
        dataHandlerCode: '  return result.data.data;',
        errorHandlerCode: '  $message.error(error.message);',
        dataSetEnabled: false,  // 是否开启多数据集
        dataSets: [],
      },
      curEditDSIdx: -1,

      formRules: {
        uniqueName: [
          { required: true, trigger: ['blur', 'change'], message: this.i18nt('designer.setting.fieldValueRequired') },
        ],
        requestURL: [
          { required: true, trigger: ['blur', 'change'], message: this.i18nt('designer.setting.fieldValueRequired') },
        ],
        requestMethod: [
          { required: true, trigger: ['blur', 'change'], message: this.i18nt('designer.setting.fieldValueRequired') },
        ],
      },
      nameRules: [
        { required: true, trigger: ['blur', 'change'], message: this.i18nt('designer.setting.fieldValueRequired') },
      ],
      valueRules: [
        { required: true, trigger: ['blur', 'change'], message: this.i18nt('designer.setting.fieldValueRequired') },
        { validator: this.validateValueInput, trigger: ['blur', 'change'] },
      ],

      showDataSourceDialogFlag: false,

      dsvJson: '{\n  \n}',
      dsResultJson: '',
      showTestDataSourceDialogFlag: false,

      showImportDSDialogFlag: false,
      importDSTemplate: '',
      clearOldDSFlag: false,  //导入后是否清空原有数据源

      showExportDSDialogFlag: false,
      activeExportTab: 'setting',
      exportDSArray: [],
      dsExportContent: '',
      dsRawExportContent: '',
      showSubscriptionServiceFlag: false,//
    }
  },
  methods: {
    showAndEditSubscriptionServiceDialog(id) {
      this.showSubscriptionServiceFlag = true
      this.$nextTick(() => {
        this.$refs.subscriptionService.handleSidebarSelect(id.toString())
      })
    },
    handleRemoveService(id) {
      this.formConfig.serviceVersionVOs.splice(this.formConfig.serviceVersionVOs.findIndex(item => item.id == id), 1)
      eventBus.$emit(SERVICE_OPERATION.DELETE, id)
    },
    // 同步服务到表单配置，弹窗服务关闭时调用
    syncServicesToFormConfig() {
      // debugger
      console.log('syncServicesToFormConfig', this.$refs.subscriptionService.cloneServiceVersionVOs)
      // this.$refs.subscriptionService.bindModelTreeToService()
      this.formConfig.serviceVersionVOs = this.$refs.subscriptionService.cloneServiceVersionVOs
      // this.updateAllWidgetsSVVOIdToCurrent()
      this.closeSubscriptionServiceDialog()
    },
    closeSubscriptionServiceDialog() {
      // this.$refs.subscriptionService.services = null
      this.showSubscriptionServiceFlag = false
      // if(handleType==='')
      /*this.$refs.subscriptionService.clearFormData(this.formConfig.services, handleType)
      this.showSubscriptionServiceFlag = false*/
    },
    async updateAllWidgetsSVVOIdToCurrent() {
      traverseAllWidgets(this.designer.widgetList, (widget) => {
        if (widget?.options?.service?.enabled) {
          console.log(11, widget)
          widget.options.service.id = this.$refs.subscriptionService.currentCurrentServiceVersionVOs.id
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
/*:deep(.ds-setting-drawer) { !* 必须加上:deep，否则不生效 *!*/
/*  right: 320px !important;*/
/*}*/

.ds-list {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  flex: 1;

  .service-item {
    display: grid;
    margin-top: 5px;
    padding: 5px;
    border: solid 1px #ccc;
    border-radius: 5px;
    row-gap: 5px;
    column-gap: 10px;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    align-items: center;

    div:nth-child(1) {
      grid-area: 1/1/2/3;
    }

    .font-bolder {
      font-weight: bolder;
      width: 100%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.ds-button-wrapper {
  text-align: center;
  margin-top: 12px;
}

.ds-form {
  :deep(.ep-form-item.is-required>.ep-form-item__label:before) {
    content: '' !important;
    margin-right: 0 !important;
  }

  :deep(.ep-form-item.is-required>.ep-form-item__label:after) {
    content: '*' !important;
    color: var(--el-color-danger);
    font-weight: bold;
  }
}

.no-left-margin :deep(.ep-form-item__content) {
  margin-left: 0 !important;
}

.rh-row, .rd-row {
  :deep(.ep-col) {
    margin: 5px 0;
  }
}

.ch-collapse :deep(.ace-editor) {
  border: 1px solid #e1e2e3;
  min-height: 120px;
}

.dh-collapse :deep(.ace-editor) {
  border: 1px solid #e1e2e3;
  min-height: 220px;
}

.eh-collapse :deep(.ace-editor) {
  border: 1px solid #e1e2e3;
  min-height: 120px;
}

.dsv-json-editor {
  margin-bottom: 12px;
}

.dsv-json-editor :deep(.ace-editor) {
  border: 1px solid #e1e2e3;
  min-height: 120px;
}

:deep(.ace-editor) {
  border: 1px solid #e1e2e3;
}

.footer-button {
  float: right;
  margin-bottom: 12px;
}

.display-block :deep(.ep-form-item__content) {
  display: block !important;
}

.dialog-footer {
  margin-top: 15px;
}

.dialog-footer-center {
  margin-top: 15px;
  text-align: center;
}

.export-ds-list {
  :deep(.ep-descriptions__content) {
    overflow-x: hidden;
    margin-bottom: 15px;
    padding: 8px;
    background: #f5f7fa;
  }

  :deep(.ep-descriptions__title) {
    font-weight: normal;
  }

  :deep(.ep-descriptions__label) {
    width: 36px !important;
  }
}

</style>
